﻿using System;
using System.Configuration;
using System.Data;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using Common;
using CommonLib;
using HCRS.DBACL;
using HCRS.Errors;
using HCRS.Implementation;
using Hubs1;
using JinJiang.BookingEngine.Services;

namespace JinJiang.BookingEngine.Web.cn
{
    public partial class CheckRates : Page
    {
        /// <summary>
        /// 图片URL
        /// </summary>
        public static string photourl = System.Configuration.ConfigurationManager.AppSettings["photourl"].ToString();
        /// <summary>
        /// 价格代码
        /// </summary>
        public string ratecode = System.Configuration.ConfigurationManager.AppSettings["ratecode"].ToString();
        /// <summary>
        /// 积分兑换比率
        /// </summary>
        static decimal exchange = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["exchange"]);

        static string IATA = System.Configuration.ConfigurationManager.AppSettings["IATA"].ToString();
        static string PIATA = System.Configuration.ConfigurationManager.AppSettings["PIATA"].ToString();
        private int ahid = 0;

        QueryXml _QueryXmlClass = new QueryXml();
        //UserClass _UserClass = new UserClass();
        HotelClass _HotelClass = new HotelClass();
        DataAccessLayer _DataAccessLayer = new DataAccessLayer();
        Functions _Functions = new Functions();
        CommonWeb _CommonClass = new CommonWeb();
        bool ppGua = false;
        bool ccGua = false;
        string userCredit = "";
        public string paymentHtml;
        int propertyID;
        public string domainurl, domain;

        protected void Page_Load(object sender, EventArgs e)
        {

            //处理价格代码(BAR|BARB,RACK)
            if (Request.UrlReferrer != null)
                domain = FGBCommon.WebDomain(false, out domainurl);

            bool foundhotel;
            string rateinfo;
            ahid = Convert.ToInt32(Request.QueryString["HotelID"]);
            ViewState["payment"] = "";
            if (!(IsPostBack))
            {
                bodyBooking.Attributes.Add("onload", "fSetOutLinkIframe('" + domain + "')");

                PageCC.Visible = false;
                pnlErr.Visible = false;
                try
                {
                    this.divPP.Visible = false;
                    int hotelID = Convert.ToInt32(Request.QueryString["HotelID"]);
                    ahid = hotelID;
                    int nights;
                    int room = Convert.ToInt32(Request.QueryString["Rooms"]);
                    int adults = Convert.ToInt32(Request.QueryString["Adult"]);
                    int chileren = Convert.ToInt32(Request.QueryString["Child"]);

                    string Chickindate = Request.QueryString["ChkIN"];
                    string Chickoutdate = Request.QueryString["ChkOUT"];
                    string rateCode = Request.QueryString["Ratecode"];
                    string spcode = Request.QueryString["spcode"] == null ? "" : Request.QueryString["spcode"];


                    //校验价格代码合法性
                    string avaRateCode = "";

                    SearchHotelClass myHotelClass = new SearchHotelClass();
                    if (!myHotelClass.RateCodeAvailable(hotelID, "hid", rateCode, out avaRateCode))
                    {
                        Response.Write("没有符合条件的房价信息（错误代码001）。");
                        Response.End();
                    }

                    if (avaRateCode != "" && avaRateCode != null)
                    {
                        rateCode = avaRateCode;
                    }
                    else
                    {
                        Response.Write("没有符合条件的房价信息（错误代码002）。");
                        Response.End();
                    }


                    if (DataAcl.Common.isserverhotel(ahid))
                        Userlogin1.Visible = true;

                    string roomCode = Request.QueryString["Roomcode"];
                    TimeSpan ts = Convert.ToDateTime(Chickoutdate) - Convert.ToDateTime(Chickindate);
                    nights = Convert.ToInt32(ts.TotalDays);

                    foundhotel = LoadHotelInfo(hotelID);
                    ckbNoSmooking.Attributes.Add("onclick", "NoSmooking(this);");
                    dpdCheckInTime.Attributes.Add("onChange", "validateCheckInTimeDo(this);");

                    //填写viewstate
                    ViewState["h_fromurl"] = "prestige.jinjianghotels.com/cn";
                    ViewState["h_subSource"] = "208";
                    ViewState["h_verifycode"] = Guid.NewGuid().ToString();// rndnum(8);
                    ViewState["h_hotelID"] = propertyID.ToString();
                    ViewState["h_children"] = chileren.ToString();
                    ViewState["h_property_id"] = propertyID.ToString();
                    ViewState["h_roomtype"] = roomCode;
                    ViewState["h_rateclass"] = rateCode;
                    ViewState["spcode"] = spcode;
                    CheckRatesOK(roomCode, rateCode, Chickindate, Chickoutdate, propertyID, nights, adults, chileren, room);

                    if (DataAcl.Common.checkexpojs(rateCode))
                        googlejs.Visible = true;
                    else
                        googlejs.Visible = false;

                }
                catch (ThreadAbortException ex)
                {
                    string message = "错误信息:" + ex.Message + ex.Source + ex.StackTrace + ";引发异常的方法:" + ex.TargetSite.ToString() + "错误模块:酒店预订checkrates.aspx ; 错误程序:PageLoad";
                    //HCRS.Errors.WebError.SendErrorEmail("酒店预订checkrates.aspx/pageload!", message);
                    HCRS.Errors.WebError.SendErrorEmail("酒店预订checkrates.aspx/pageload!" + message);

                    Loger.AddTextLog(message);

                }
                catch (Exception ex)
                {


                    ShowErr("由于参数缺失或网络延迟，未能执行酒店价格查询，请您重试。");
                    string message = "错误信息:" + ex.Message + ex.Source + ex.StackTrace + ";引发异常的方法:" + ex.TargetSite.ToString() + "错误模块:酒店预订checkrates.aspx ; 错误程序:PageLoad";
                    HCRS.Errors.WebError.SendErrorEmail("酒店预订checkrates.aspx/pageload!", message);

                    Loger.AddTextLog(message);
                }


            }

        }

        private void CheckRatesOK(string roomType, string rateClass, string Chickindate, string Chickoutdate, int propertyID, int nights, int adults, int chileren, int room)
        {
            string errmsg;
            DataSet myDataSet;
            bool showGuestInfo = true;
            string plandesc;
            string planstatus;
            string roomdesc;
            string roomname;
            string ratedesc;
            string ratename;
            string responsexml;
            string TempCurrenyCode = "";
            string BreakFirst = "";

            GetRateInfo info = new GetRateInfo();
            info.adults = adults;
            info.checkin = Chickindate;
            info.children = chileren;
            //info.currencycode = "";
            //info.filter = "0";
            info.iata = CommonFun.IATA();
            info.language = 0;
            info.nights = nights;
            info.pid = propertyID;
            info.ratecodes = rateClass.Replace("|", ",").Split(',');
            info.roomcodes = roomType.Split(',');
            info.rooms = room;

            myDataSet = HCRS.Implementation.OrderClass.getonlineratemap(info, out errmsg);

            if (errmsg == "Error" || errmsg == "noResponse")
            {
                divpric.InnerHtml = "酒店客房信息实时状态查询失败，请您刷新页面重试。";
            }
            else if (errmsg == "noEnoughAvailRoom")
            {
                divpric.InnerHtml = "当前酒店客房可用数量或时间段不符合您的预订要求，请重新查询";

            }
            else if (myDataSet.Tables[1].Select("gua='CP'").Length > 0) //过滤公司担保
            {
                divpric.InnerHtml = "当前酒店客房不可用，请重新查询";
            }
            else if (errmsg == "")
            {
                if (myDataSet.Tables[0].Rows.Count != 0)
                {
                    plandesc = myDataSet.Tables[0].Rows[0]["planDesc"].ToString();
                    planstatus = myDataSet.Tables[0].Rows[0]["planStatus"].ToString();
                    roomdesc = myDataSet.Tables[0].Rows[0]["roomDesc"].ToString();
                    roomname = myDataSet.Tables[0].Rows[0]["roomName"].ToString();
                    ratedesc = myDataSet.Tables[0].Rows[0]["rateDesc"].ToString();
                    ratename = myDataSet.Tables[0].Rows[0]["rateName"].ToString();

                    string data = "";
                    bool noteaque = false;
                    bool noALLOT = false;
                    bool noAvStat = false;
                    bool noAvStatLos = false;
                    string GUARule = "RH";
                    string CXLRule = "NP";
                    decimal totalMount = 0;
                    string dailyPrice = "";


                    for (int i = 0; i < myDataSet.Tables[1].Rows.Count; i++)
                    {

                        decimal xmlpriceNoTax = decimal.Round(Convert.ToDecimal(myDataSet.Tables[1].Rows[i]["priceNoTax"].ToString()), 2);
                        string xmlGua = myDataSet.Tables[1].Rows[i]["Gua"].ToString();
                        string xmlCxl = myDataSet.Tables[1].Rows[i]["Cxl"].ToString();

                        totalMount += xmlpriceNoTax;
                        dailyPrice += "|" + myDataSet.Tables[1].Rows[i]["Availdate"].ToString() + "," + xmlpriceNoTax.ToString();

                        TempCurrenyCode = myDataSet.Tables[1].Rows[i]["currencycode"].ToString();
                        BreakFirst += "," + myDataSet.Tables[1].Rows[i]["breakfastnum"].ToString();
                        myDataSet.Tables[1].Rows[i]["Gua"] = FGBCommon.GetGuaImage(xmlGua);
                    }

                    GUARule = myDataSet.Tables[0].Rows[0]["resvgua"].ToString();
                    CXLRule = myDataSet.Tables[0].Rows[0]["resvcxl"].ToString();

                    CheckGua(GUARule);

                    if (ccGua)
                    {

                        PageCC.Visible = true;

                    }

                    H_ratelist _H_ratelist = new H_ratelist();
                    divpric.InnerHtml = _H_ratelist.FIT_GetRate(myDataSet.Tables[1], Chickindate, Chickoutdate, nights, 0);

                    #region 保证金制度描述
                    string guarrule = _HotelClass.guarruledetail(propertyID, GUARule);
                    GUAdesc.InnerHtml = guarrule;
                    //h_GuaranteePolicy.Value = guarrule;
                    //h_Guarantee.Value = GUARule;
                    #endregion

                    #region 取消制度描述
                    string cxl = _HotelClass.cxlruledetail(propertyID, CXLRule);

                    CXLdesc.InnerHtml = cxl;


                    #endregion

                    #region 税金制度
                    _DataAccessLayer.ClearParameter();
                    _DataAccessLayer.addNewParameter("@Property_id", propertyID);
                    _DataAccessLayer.addNewParameter("@languagetype", 0);
                    DataTable MydatatableTAX = _DataAccessLayer.RunStoreDataTable("selectTAXDFB");
                    foreach (DataRow dr in MydatatableTAX.Rows)
                    {
                        string typeCode = dr["typeCode"].ToString();
                        switch (typeCode)
                        {
                            case "ST":
                                typeCode = "州立税";
                                break;

                            case "CT":
                                typeCode = "城市税";
                                break;

                            case "CH":
                                typeCode = "城市酒店费用";
                                break;
                            case "CO":
                                typeCode = "县税";
                                break;
                            case "FT":
                                typeCode = "联邦税";
                                break;
                            case "SA":
                                typeCode = "销售税";
                                break;
                            case "RF":
                                typeCode = "求助费用";
                                break;
                            case "SV":
                                typeCode = "追加罚款";
                                break;
                            case "SC":
                                typeCode = "服务费用";
                                break;
                            case "OT":
                                typeCode = "入住费";
                                break;
                            case "MF":
                                typeCode = "维护费";
                                break;
                            case "EC":
                                typeCode = "充能";
                                break;
                            case "PR":
                                typeCode = "打包价格费用";
                                break;
                            case "BT":
                                typeCode = "床税";
                                break;
                            case "VA":
                                typeCode = "增值税";
                                break;
                            case "SU":
                                typeCode = "额外费用";
                                break;


                        }
                        dr["typeCode"] = typeCode;

                        string application = dr["application"].ToString();
                        switch (application)
                        {
                            case "RS":
                                application = "每间/每次住宿";
                                break;

                            case "RN":
                                application = "每间/每晚";
                                break;

                            case "PS":
                                application = "每人/每次";
                                break;
                            case "PN":
                                application = "每人/每晚";
                                break;


                        }
                        dr["application"] = application;

                        string feetype = dr["method"].ToString();
                        switch (feetype)
                        {
                            case "P":
                                feetype = "按" + application + "收取消费金额的" + dr["amount"].ToString() + "％作为" + typeCode;
                                break;

                            case "M":
                                feetype = "按" + application + "收取金额" + dr["amount"].ToString() + "元，作为" + typeCode;
                                break;


                        }
                        dr["method"] = feetype;
                        Taxdesc.InnerHtml += typeCode + ": " + feetype + "<br />";

                    }

                    #endregion

                    #region 总价/每日价格/房型描述/价格描述

                    totalMount = totalMount * room;
                    //divpric.InnerHtml = FormatDate(cachetable, Chickindate, Chickoutdate, nights);
                    TotalPrice.InnerHtml = totalMount.ToString();
                    //LabelAdults.Text = adults.ToString() ;
                    //LabelChileren.Text = chileren.ToString();
                    LabelChickIn.Text = Chickindate;
                    LabelCheckout.Text = Chickoutdate;
                    LabelNights.Text = nights.ToString();
                    lblRoomDesc.Text = roomdesc;
                    LabelPlanDesc.Text = plandesc;
                    LabelRoom1.Text = room.ToString() + "间，每间" + adults.ToString() + "人";
                    LabelRoom.Text = room.ToString();
                    lblRoomName.Text = roomname;
                    LabCurreny.Text = TempCurrenyCode;

                    if (this.divPP.Visible)
                    {
                        this.lblPrepay.Text = totalMount.ToString();
                    }
                    #endregion

                    #region 填写表单各数据项，并写入viewstate供回传
                    decimal Scores = totalMount * exchange;
                    ltrScores.Text = "<script language=\"javascript\" type=\"text/javascript\">var Scores=" + Scores + ";</script>";
                    LabelAdults.Text = adults.ToString();
                    LabelChickIn.Text = Chickindate;
                    LabelCheckout.Text = Chickoutdate;
                    LabelNights.Text = nights.ToString();
                    LabelRoomDesc.Text = roomdesc;
                    LabelPlanDesc.Text = plandesc;
                    //LabelRoom.Text = room.ToString();
                    LabelRoomName.Text = roomname;

                    ViewState["h_Guarantee"] = GUARule;
                    ViewState["h_TotalMount"] = totalMount.ToString();
                    ViewState["h_DailyPrice"] = dailyPrice;
                    ViewState["Scores"] = Scores;
                    ViewState["h_BreakFirst"] = BreakFirst;
                    ViewState["h_CurrencyCode"] = TempCurrenyCode;
                    #endregion


                }
            }
            else
            {
                ShowErr("暂时无法连接到中央预订系统，请稍候再试。");
            }
        }


        private bool LoadHotelInfo(int hotelID)
        {
            #region 读取酒店信息，如果没有对应的酒店，则输出错误提示。


            _DataAccessLayer.ClearParameter();
            _DataAccessLayer.addNewParameter("@Hotel_ID", hotelID);
            DataTable MydatatableHotel = _DataAccessLayer.RunStoreDataTable("FGB_JJ_selectHotel");
            if (MydatatableHotel.Rows.Count > 0)
            {

                lblHotelName.Text = MydatatableHotel.Rows[0]["Title"].ToString();
                Hotel_titletel.InnerHtml = "电话：" + MydatatableHotel.Rows[0]["Phone"].ToString();
                address1.InnerHtml = "地址：" + MydatatableHotel.Rows[0]["Address1"].ToString();
                fax.InnerHtml = "传真：" + MydatatableHotel.Rows[0]["fax"].ToString();
                subtitle.InnerHtml = "简介：" + MydatatableHotel.Rows[0]["subtitle"].ToString();
                slogan.InnerHtml = new HCRS.Implementation.HotelClass().GetSloganResv(Convert.ToInt32(MydatatableHotel.Rows[0]["pid"].ToString()), 0);// MydatatableHotel.Rows[0]["subtitle"].ToString();
                imgHotel.ImageUrl = photourl + MydatatableHotel.Rows[0]["photourl"].ToString();
                propertyID = Convert.ToInt32(MydatatableHotel.Rows[0]["pid"].ToString());
                lblHoldtime.Text = DataAcl.Common.formatCheckInOut(MydatatableHotel.Rows[0]["holdtime"].ToString());
                StringBuilder holdtimeScript = new StringBuilder();
                holdtimeScript.Append("<script language=\"JavaScript\" type=\"text/JavaScript\">");
                holdtimeScript.Append("function validateCheckInTimeDo(obj)");
                holdtimeScript.Append("{");
                holdtimeScript.Append("var s=obj.value;");
                holdtimeScript.Append("if (s>" + MydatatableHotel.Rows[0]["holdtime"].ToString().Replace(":", "") + ") ");
                holdtimeScript.Append("{");
                holdtimeScript.Append("document.getElementById(\"checkintime\").innerHTML=\"<font color=DodgerBlue>您所选择的抵店时间已超过酒店的保留时间，房间的安排将视入住情况安排，如您需要保留您的预订，请做担保，详情请致电800-819-5677, 400-670-5677</font>\";");
                holdtimeScript.Append("}");
                holdtimeScript.Append("else ");
                holdtimeScript.Append("document.getElementById(\"checkintime\").innerHTML=\"\";");
                holdtimeScript.Append("}");
                holdtimeScript.Append("</script>");
                ClientScript.RegisterStartupScript(this.GetType(), "123", holdtimeScript.ToString());

                return true;
            }
            else
            {
                return false;
            }


            #endregion
        }

        public void CheckGua(string guaRule)
        {
            #region 如果保证金制度是CC,显示信用卡输入筐，否则不显示
            if (guaRule.IndexOf("DP") >= 0 || guaRule.IndexOf("PP") >= 0)
            {

                //查询保证金制度描述
                PAYdesc.InnerHtml = "<font color=red>本房型需预付费保证</font>";
                paymentHtml = "<tr><td ><span class='redtype'><strong>对于预订本房型酒店要求预付费，未完成在线预付操作将无法完成预订。</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";
                ppGua = true;
                ViewState["payment"] = "PP";
                this.divPP.Visible = true;
                //this.divPPScore.Visible = false;
            }
            else if (guaRule.IndexOf("CC") >= 0)
            {
                PAYdesc.InnerHtml = "<font color=red>本房型需信用卡保证</font>";
                ccGua = true;
            }
            //else
            //{
            //    PAYdesc.InnerHtml = "无需信用卡，无需预付费保证";
            //    paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>我要预付费来确保我的预订</td></tr>";

            //}
            //if (guaRule.IndexOf("CC") < 0)
            //{
            //    // CreditCard.Controls.Clear();

            //    if (guaRule.IndexOf("DP") < 0 || guaRule.IndexOf("PP") < 0)
            //    {

            //        //查询保证金制度描述
            //        PAYdesc.InnerHtml = "无需信用卡，无需预付费保证";
            //        paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>我要预付费来确保我的预订</td></tr>";

            //    }
            //    else
            //    {
            //        PAYdesc.InnerHtml = "<font color=red>本房型需预付费保证</font>";
            //        paymentHtml = "<tr><td ><span class='redtype'><strong>对于预订本房型酒店要求预付费，未完成在线预付操作将无法完成预订。</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";

            //    }
            //}

            #endregion
        }

        public void Payment(string guaRule)
        {
            #region 如果保证金制度代码包含CC和DP则强制要求付费

            if (guaRule.IndexOf("CG") > 0 || guaRule.IndexOf("DP") > 0)
            {
                paymentHtml = "<tr><td ><span class='redtype'><strong>对于预订本房型酒店要求预付费，未完成在线预付操作将无法完成预订。</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";

            }
            else
            {
                paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>我要预付费来确保我的预订</td></tr>";
            }

            #endregion
        }

        protected override PageStatePersister PageStatePersister
        {
            get
            {
                return new HiddenFieldPageStatePersister(this);
            }
        }

        protected void btnOrder_Click(object sender, EventArgs e)
        {

            int adult;
            int children;
            int room;
            int nights;
            int property_id;

            string rateclass = ViewState["h_rateclass"].ToString();
            string roomtype = ViewState["h_roomtype"].ToString();

            string checkIn = Convert.ToDateTime(LabelChickIn.Text).ToString("yyyy-MM-dd");
            string checkOut = Convert.ToDateTime(LabelCheckout.Text).ToString("yyyy-MM-dd");

            string totalMount = ViewState["h_TotalMount"].ToString();
            string dailyPrice = ViewState["h_DailyPrice"].ToString();

            string plandesc = LabelPlanDesc.Text;
            string roomname = LabelRoomName.Text;
            string roomdesc = LabelRoomDesc.Text;
            string cancellationPolicy = CXLdesc.InnerHtml;
            string guaranteePolicy = GUAdesc.InnerHtml;
            string taxPolicy = Taxdesc.InnerHtml;
            string fromurl = ViewState["h_fromurl"].ToString();
            string subSource = ViewState["h_subSource"].ToString();
            string verifycode = ViewState["h_verifycode"].ToString();
            string firstName = _CommonClass.VerifySQL(FirstName.Text);
            string lastName = _CommonClass.VerifySQL(LastName.Text);
            string guestEmail = _CommonClass.VerifySQL(GuestEmail.Text);
            string guestPhone = _CommonClass.VerifySQL(GuestPhone.Text);
            string guestMP = _CommonClass.VerifySQL(txtMobile.Text);
            string guestAddressLine1 = _CommonClass.VerifySQL(GuestAddressLine1.Text);
            string remarks = _CommonClass.VerifySQL(Server.HtmlDecode(this.remark.Text.Replace("%", "％")));
            string spcode = ViewState["spcode"].ToString();
            string currencyCode = ViewState["h_CurrencyCode"].ToString();
            string breakFirst = ViewState["h_BreakFirst"].ToString();
            breakFirst = breakFirst.Trim(new char[] { ',' });

            string resvinfo = "";
            if (_CommonClass.VerifySQL(this.dpdCheckInTime.Text) != "")
            {
                Hubs1.ResvInfoBean resvinfobean = new Hubs1.ResvInfoBean();
                resvinfobean.holdTime = DataAcl.Common.formatCheckInOut(this.dpdCheckInTime.Text);
                resvinfo = Hubs1.ResvInfoUtil.GetResvInfoXML(resvinfobean);
            }

            int userID;
            string userType;
            string propertyname = "";
            string propertyname_e = "";
            string ccType = "";
            string ccNumber = "";
            string ccName = "";
            string ccMonth = "";
            string ccYear = "";
            string spresponse = "";

            DateTime updatetime = new DateTime();
            updatetime = DateTime.Now;

            if (_CommonClass.VerifySQL(this.dpdCheckInTime.Text) != "")
            {
                remarks += "<br/>最晚抵达时间：" + DataAcl.Common.formatCheckInOut(this.dpdCheckInTime.Text);
            }
            if (_CommonClass.VerifySQL(this.txtAirInfo.Text) != "")
            {
                remarks += "<br/>航班信息：" + this.txtAirInfo.Text;
            }
            if (this.ckbNoSmooking.Checked)
            {
                remarks += "<br/>需要无烟房";
            }
            if (guestMP != "")
            {
                remarks += "<br/>手机号码：" + guestMP;
            }

            userID = 0;
            userType = "";

            if (LabelAdults.Text == "")
            {
                adult = 0;
            }
            else
            {
                adult = Convert.ToInt32(LabelAdults.Text);
            }
            if (ViewState["h_children"].ToString() == "")
            {
                children = 0;
            }
            else
            {
                children = Convert.ToInt32(ViewState["h_children"]);
            }
            if (LabelRoom.Text == "")
            {
                room = 0;
            }
            else
            {
                room = Convert.ToInt32(LabelRoom.Text);
            }
            if (LabelNights.Text == "")
            {
                nights = 0;
            }
            else
            {
                nights = Convert.ToInt32(LabelNights.Text);
            }
            if (ViewState["h_property_id"].ToString() == "")
            {
                property_id = 0;
            }
            else
            {
                property_id = Convert.ToInt32(ViewState["h_property_id"]);
            }

            decimal scores = Convert.ToDecimal(ViewState["Scores"]);
            CheckGua(ViewState["h_Guarantee"].ToString());

            if (ppGua)
            {
                ccType = "PP";
                ccNumber = "-";
                ccMonth = "00";
                ccYear = "00";
                ccName = "-";
            }
            else if (ccGua)
            {

                ccType = PageCC.ccType;
                ccName = PageCC.ccName;
                ccNumber = PageCC.ccNumber;
                ccMonth = PageCC.ccMonth;
                ccYear = PageCC.ccYear;

            }
            else
            {
                ccType = "VI";
                ccNumber = "-";
                ccMonth = "00";
                ccYear = "00";
                ccName = "-";
            }

            try
            {
                string sql = "select title,title_e from hotel where pid='" + property_id + "'";
                DataTable dtHotel = _DataAccessLayer.RunSqlDataTable(sql);

                if (dtHotel.Rows.Count > 0)
                {
                    propertyname = dtHotel.Rows[0]["title"].ToString();
                    propertyname_e = dtHotel.Rows[0]["title_e"].ToString();
                }

                if (_DataAccessLayer.RunSqlExists("select top 1 * from resvlog where verifycode='" + verifycode + "'"))
                {
                    if (_DataAccessLayer.RunSqlExists("select top 1 * from resvlog where verifycode='" + verifycode + "' and confnum =''"))
                    {
                        spresponse = SP_ResvLog_Upd(breakFirst, currencyCode, userID, userType, property_id, roomtype, rateclass, checkIn, checkOut, updatetime.ToString(), nights, room, firstName, lastName, guestEmail, guestPhone, guestMP, guestAddressLine1, "", "NA", "NA", "NA", "NA", ccType, ccNumber, ccName, ccYear, ccMonth, "", IATA, resvinfo, remarks, "", "", "", propertyname, propertyname_e, totalMount, dailyPrice, adult, children, plandesc, roomname, roomdesc, cancellationPolicy, guaranteePolicy, taxPolicy, "", fromurl, 0, subSource, "", "", verifycode);

                    }
                }
                else
                {
                    spresponse = SP_ResvLog_Add(breakFirst, currencyCode, scores, userID, userType, property_id, roomtype, rateclass, checkIn, checkOut, updatetime.ToString(), nights, room, firstName, lastName, guestEmail, guestPhone, guestMP, guestAddressLine1, "", "NA", "NA", "NA", "NA", ccType, ccNumber, ccName, ccYear, ccMonth, "", IATA, resvinfo, remarks, "", "", "", propertyname, propertyname_e, totalMount, dailyPrice, adult, children, plandesc, roomname, roomdesc, cancellationPolicy, guaranteePolicy, taxPolicy, "", fromurl, 0, subSource, "", "", verifycode);
                }

                if (spresponse == "")
                {
                    Response.Redirect("NewResvDo.aspx?&verifycode=" + verifycode + "&fax=" + this.txtFax.Text +
                        "&wd=" + System.Web.HttpUtility.UrlEncode(domainurl) + "&score=" + scores);
                }
                else
                {
                    ShowErr("不能正确保存预订信息时候，请您重试。" + spresponse);

                    Loger.AddTextLog(spresponse);

                }
            }
            catch (Exception ex)
            {
                Loger.AddTextLog(ex.Message);
            }


        }

        private void ShowErr(string errmsg)
        {
            // pnlGuestInfo.Visible = false;
            //chkChange.Visible = false;
            pnlErr.Visible = true;
            lblErr.Text = errmsg;
        }

        private string SP_ResvLog_Add(string breakFirst, string currencyCode, decimal scores, int userid, string usertype, int propertyid, string roomtype, string rateclass, string starttime, string deptime, string updatetime, int nights, int room, string guestfirstname, string guestlastname, string guestemail, string guestphone, string guestMP, string guestaddressline1, string guestaddressline2, string guestcity, string guestcountry, string gueststate, string guestzip, string cctype, string ccnumber, string ccname, string ccexpyear, string ccexpmonth, string frequentguestid, string iata, string resvinfo, string remarks, string confnum, string cxlnum, string status, string propertyname, string propertyname_e, string totalmount, string dailyprice, int adults, int children, string plandesc, string roomname, string roomdesc, string canclerule, string guaranteerule, string taxrule, string incomingcall, string fromurl, int deleted, string SubSource, string lastuser, string lastusertype, string verifycode)
        {
            //Email _Email = new Email();

            bool islock = true;
            string freezeno = "";
            bool isexec = false;
            bool isscore = (Request.Form.Get("chkIsScore") != null);

            string spcode = ViewState["spcode"].ToString();

            bool isspecial = (spcode.Length > 0);

            string errmsg = "";
            string cardnumber = LoginInfo.Member != null ? LoginInfo.Member.UserId : string.Empty;
            string cardclass = "", cardclassname = "";

            if (cardnumber != "" && cardnumber != null)
            {
                //lakeport.WebReference.MemberSummery mms = new WestLake.LakeMember().memberconsume(cardnumber);
                cardclass = LoginInfo.Member != null ? LoginInfo.Member.CardLevel : string.Empty;
                cardclassname = LoginInfo.Member != null ? LoginInfo.Member.CardLevel : string.Empty;
            }


            string jremark = "";
            string comment = "";

            if (cardnumber.Length > 0 && DataAcl.Common.isserverhotel(ahid))
            {
                iata = PIATA;
                //jremark += "<br/>【+】";
                jremark += "<br/>此订单为常客预定";
                jremark += "<br/> 常客卡号为:" + cardnumber;
                jremark += "<br/>卡等级:" + cardclassname;
                if (isspecial)
                {
                    jremark += "<br/>促销代码：" + spcode;
                }
                if (isscore)
                {
                    jremark += "<br/>积分兑换房间，花费<font color=red>" + scores.ToString() + "</font>积分<br>预授权号:" + freezeno;
                }
                remarks += jremark;
                comment = GetspecialXml(cardnumber, cardclass, (isscore ? "1" : "0"), (room * nights).ToString(), scores.ToString(), freezeno, spcode, "", "", "", "", "", "", "", "");
            }

            _DataAccessLayer.ClearParameter();
            _DataAccessLayer.addNewParameter("@userid", userid);
            _DataAccessLayer.addNewParameter("@usertype", usertype, 50);
            _DataAccessLayer.addNewParameter("@propertyid", propertyid);
            _DataAccessLayer.addNewParameter("@roomtype", roomtype, 50);
            _DataAccessLayer.addNewParameter("@rateclass", rateclass, 50);
            _DataAccessLayer.addNewParameter("@starttime", starttime, 10);
            _DataAccessLayer.addNewParameter("@deptime", deptime, 10);
            _DataAccessLayer.addNewParameter("@updatetime", Convert.ToDateTime(updatetime).ToString("u").Replace("Z", ""), 20);
            _DataAccessLayer.addNewParameter("@nights", nights);
            _DataAccessLayer.addNewParameter("@room", room);
            _DataAccessLayer.addNewParameter("@guestfirstname", guestfirstname, 50);
            _DataAccessLayer.addNewParameter("@guestlastname", guestlastname, 50);
            _DataAccessLayer.addNewParameter("@guestemail", guestemail, 50);
            _DataAccessLayer.addNewParameter("@guestphone", guestphone, 50);
            _DataAccessLayer.addNewParameter("@guestMP", guestMP, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline1", guestaddressline1, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline2", guestaddressline2, 50);
            _DataAccessLayer.addNewParameter("@guestcity", guestcity, 50);
            _DataAccessLayer.addNewParameter("@guestcountry", guestcountry, 50);
            _DataAccessLayer.addNewParameter("@gueststate", gueststate, 50);
            _DataAccessLayer.addNewParameter("@guestzip", guestzip, 50);
            _DataAccessLayer.addNewParameter("@cctype", cctype, 50);
            _DataAccessLayer.addNewParameter("@ccnumber", ccnumber, 50);
            _DataAccessLayer.addNewParameter("@ccname", ccname, 50);
            _DataAccessLayer.addNewParameter("@ccexpyear", ccexpyear, 50);
            _DataAccessLayer.addNewParameter("@ccexpmonth", ccexpmonth, 50);
            _DataAccessLayer.addNewParameter("@frequentguestid", frequentguestid, 50);
            _DataAccessLayer.addNewParameter("@iata", iata, 50);

            _DataAccessLayer.addNewParameter("@resvinfo", resvinfo, 500);

            _DataAccessLayer.addNewParameter("@remarks", remarks);
            _DataAccessLayer.addNewParameter("@confnum", confnum, 50);
            _DataAccessLayer.addNewParameter("@cxlnum", cxlnum, 50);
            _DataAccessLayer.addNewParameter("@status", status, 50);
            _DataAccessLayer.addNewParameter("@propertyname", propertyname, 500);
            _DataAccessLayer.addNewParameter("@propertyname_e", propertyname_e, 500);
            _DataAccessLayer.addNewParameter("@totalmount", totalmount, 50);
            _DataAccessLayer.addNewParameter("@dailyprice", dailyprice, 500);
            _DataAccessLayer.addNewParameter("@adults", adults);
            _DataAccessLayer.addNewParameter("@children", children);
            _DataAccessLayer.addNewParameter("@plandesc", plandesc, 500);
            _DataAccessLayer.addNewParameter("@roomname", roomname, 500);
            _DataAccessLayer.addNewParameter("@roomdesc", roomdesc, 500);
            _DataAccessLayer.addNewParameter("@canclerule", canclerule, 500);
            _DataAccessLayer.addNewParameter("@guaranteerule", guaranteerule, 500);
            _DataAccessLayer.addNewParameter("@taxrule", taxrule, 500);
            _DataAccessLayer.addNewParameter("@incomingcall", incomingcall, 50);
            _DataAccessLayer.addNewParameter("@fromurl", fromurl, 255);
            _DataAccessLayer.addNewParameter("@deleted", deleted);
            _DataAccessLayer.addNewParameter("@SubSource", SubSource, 50);
            _DataAccessLayer.addNewParameter("@lastuser", lastuser, 50);
            _DataAccessLayer.addNewParameter("@lastusertype", lastusertype, 50);
            _DataAccessLayer.addNewParameter("@verifycode", verifycode, 50);
            _DataAccessLayer.addNewParameter("@getstatus", 0);
            _DataAccessLayer.addNewParameter("@flgorder", 0);
            _DataAccessLayer.addNewParameter("@departure", "", 10);
            _DataAccessLayer.addNewParameter("@payment", ViewState["payment"].ToString(), 50);
            _DataAccessLayer.addNewParameter("@cardnumber", cardnumber);
            _DataAccessLayer.addNewParameter("@isscore", isscore);
            _DataAccessLayer.addNewParameter("@isspecial", isspecial);
            _DataAccessLayer.addNewParameter("@jremark", jremark, 500);
            _DataAccessLayer.addNewParameter("@score", scores);
            _DataAccessLayer.addNewParameter("@islock", islock);
            _DataAccessLayer.addNewParameter("@isexec", isexec);
            _DataAccessLayer.addNewParameter("@freezeno", freezeno, 50);
            _DataAccessLayer.addNewParameter("@comment", comment, 500);

            _DataAccessLayer.addNewParameter("@CurrencyCode", currencyCode, 5);
            _DataAccessLayer.addNewParameter("@Breakfast", breakFirst, 50);
            _DataAccessLayer.RunStore("FGB_JJ_ResvLog_Add");
            //CommonDataAccess.ExecInsertProcedure("FGB_JJ_ResvLog_Add", "@,,,,,", "string,int,", new object[] { });


            if (_DataAccessLayer.ErrorMsg.Length > 2)
            {
                return _DataAccessLayer.ErrorMsg;
            }
            else
            {

                //冻结积分

                if (isscore)
                {
                    //islock=;//积分冻结

                    //if (WestLake.LakeScore.LockScore(verifycode, scores, cardnumber, out freezeno))
                    //{
                    //    //_Email.SendMail("积分冻结成功！verifycode=" + verifycode + ", scores=" + scores + ",freezeno=" + freezeno + ", cardno=" + cardnumber, "New");

                    //    Loger.AddTextLog("积分冻结成功！verifycode=" + verifycode + ", scores=" + scores + ",freezeno=" + freezeno + ", cardno=" + cardnumber);

                    //    isexec = true;
                    //}
                    //else
                    //{

                    //    //_Email.SendMail("积分冻结失败！verifycode=" + verifycode + ", scores=" + scores + ",freezeno=" + freezeno + ", cardno=" + cardnumber, "New");
                    //    Loger.AddTextLog("积分冻结失败！verifycode=" + verifycode + ", scores=" + scores + ",freezeno=" + freezeno + ", cardno=" + cardnumber);

                    //    return "积分冻结失败，暂时无法使用积分兑换，请稍后预订或检查积分总额是否不足";


                    //}
                    Loger.AddTextLog("积分冻结成功！verifycode=" + verifycode + ", scores=" + scores + ",freezeno=" + freezeno + ", cardno=" + cardnumber);

                    isexec = true;
                }
                else
                {
                    scores = 0;
                    isexec = true;
                    islock = true;
                }

                return errmsg;
            }

        }

        private string SP_ResvLog_Upd(string breakFirst, string currencyCode, int userid, string usertype, int propertyid, string roomtype, string rateclass, string starttime, string deptime, string updatetime, int nights, int room, string guestfirstname, string guestlastname, string guestemail, string guestphone, string guestMP, string guestaddressline1, string guestaddressline2, string guestcity, string guestcountry, string gueststate, string guestzip, string cctype, string ccnumber, string ccname, string ccexpyear, string ccexpmonth, string frequentguestid, string iata, string resvinfo, string remarks, string confnum, string cxlnum, string status, string propertyname, string propertyname_e, string totalmount, string dailyprice, int adults, int children, string plandesc, string roomname, string roomdesc, string canclerule, string guaranteerule, string taxrule, string incomingcall, string fromurl, int deleted, string SubSource, string lastuser, string lastusertype, string verifycode)
        {
            string errmsg = "";
            _DataAccessLayer.ClearParameter();
            _DataAccessLayer.addNewParameter("@userid", userid);
            _DataAccessLayer.addNewParameter("@usertype", usertype, 50);
            _DataAccessLayer.addNewParameter("@propertyid", propertyid);
            _DataAccessLayer.addNewParameter("@roomtype", roomtype, 50);
            _DataAccessLayer.addNewParameter("@rateclass", rateclass, 50);
            _DataAccessLayer.addNewParameter("@starttime", starttime, 10);
            _DataAccessLayer.addNewParameter("@deptime", deptime, 10);
            _DataAccessLayer.addNewParameter("@updatetime", Convert.ToDateTime(updatetime).ToString("u").Replace("Z", ""), 20);
            _DataAccessLayer.addNewParameter("@nights", nights);
            _DataAccessLayer.addNewParameter("@room", room);
            _DataAccessLayer.addNewParameter("@guestfirstname", guestfirstname, 50);
            _DataAccessLayer.addNewParameter("@guestlastname", guestlastname, 50);
            _DataAccessLayer.addNewParameter("@guestemail", guestemail, 50);
            _DataAccessLayer.addNewParameter("@guestphone", guestphone, 50);
            _DataAccessLayer.addNewParameter("@guestMP", guestMP, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline1", guestaddressline1, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline2", guestaddressline2, 50);
            _DataAccessLayer.addNewParameter("@guestcity", guestcity, 50);
            _DataAccessLayer.addNewParameter("@guestcountry", guestcountry, 50);
            _DataAccessLayer.addNewParameter("@gueststate", gueststate, 50);
            _DataAccessLayer.addNewParameter("@guestzip", guestzip, 50);
            _DataAccessLayer.addNewParameter("@cctype", cctype, 50);
            _DataAccessLayer.addNewParameter("@ccnumber", ccnumber, 50);
            _DataAccessLayer.addNewParameter("@ccname", ccname, 50);
            _DataAccessLayer.addNewParameter("@ccexpyear", ccexpyear, 50);
            _DataAccessLayer.addNewParameter("@ccexpmonth", ccexpmonth, 50);
            _DataAccessLayer.addNewParameter("@frequentguestid", frequentguestid, 50);
            _DataAccessLayer.addNewParameter("@iata", iata, 50);
            _DataAccessLayer.addNewParameter("@resvinfo", resvinfo, 500);
            _DataAccessLayer.addNewParameter("@remarks", remarks);
            _DataAccessLayer.addNewParameter("@confnum", confnum, 50);
            _DataAccessLayer.addNewParameter("@cxlnum", cxlnum, 50);
            _DataAccessLayer.addNewParameter("@status", status, 50);
            _DataAccessLayer.addNewParameter("@propertyname", propertyname, 500);
            _DataAccessLayer.addNewParameter("@propertyname_e", propertyname_e, 500);
            _DataAccessLayer.addNewParameter("@totalmount", totalmount, 50);
            _DataAccessLayer.addNewParameter("@dailyprice", dailyprice, 500);
            _DataAccessLayer.addNewParameter("@adults", adults);
            _DataAccessLayer.addNewParameter("@children", children);
            _DataAccessLayer.addNewParameter("@plandesc", plandesc, 500);
            _DataAccessLayer.addNewParameter("@roomname", roomname, 500);
            _DataAccessLayer.addNewParameter("@roomdesc", roomdesc, 500);
            _DataAccessLayer.addNewParameter("@canclerule", canclerule, 500);
            _DataAccessLayer.addNewParameter("@guaranteerule", guaranteerule, 500);
            _DataAccessLayer.addNewParameter("@taxrule", taxrule, 500);
            _DataAccessLayer.addNewParameter("@incomingcall", incomingcall, 50);
            _DataAccessLayer.addNewParameter("@fromurl", fromurl, 255);
            _DataAccessLayer.addNewParameter("@deleted", deleted);
            _DataAccessLayer.addNewParameter("@SubSource", SubSource, 50);
            _DataAccessLayer.addNewParameter("@lastuser", lastuser, 50);
            _DataAccessLayer.addNewParameter("@lastusertype", lastusertype, 50);
            _DataAccessLayer.addNewParameter("@verifycode", verifycode, 50);

            _DataAccessLayer.addNewParameter("@CurrencyCode", currencyCode, 5);
            _DataAccessLayer.addNewParameter("@Breakfast", breakFirst, 50);

            _DataAccessLayer.RunStore("FGB_JJ_ResvLog_Mod");

            if (_DataAccessLayer.ErrorMsg.Length > 2)
            {
                //Response.Write(_DataAccessLayer.ErrorMsg); //输出错误信息
                return _DataAccessLayer.ErrorMsg;
            }
            else
            {
                return errmsg;
            }

        }


        private string GetspecialXml(string memberno, string memberclass, string isfree, string room, string score, string freezeno, string salecode, string airtype, string airno, string airamount, string f1, string f2, string f3, string f4, string f5)
        {
            StringBuilder str = new StringBuilder();
            str.Append("<memberinfo> ");
            str.Append(" <memberno>" + memberno + "</memberno> ");
            str.Append(" <memberclass>" + memberclass + "</memberclass> ");
            str.Append(" <isfree>");
            if (isfree == "1")
                str.Append("Y");
            else
                str.Append("N");
            str.Append("</isfree> ");
            str.Append(" <room>" + room + "</room> ");
            str.Append(" <score>" + score + "</score> ");
            str.Append(" <freezeno>" + freezeno + "</freezeno> ");
            str.Append(" <salecode>" + salecode + "</salecode> ");
            str.Append(" <airtype>" + airtype + "</airtype> ");
            str.Append(" <airno>" + airno + "</airno> ");
            str.Append(" <airamount>" + airamount + "</airamount> ");
            str.Append("<f1></f1>");
            str.Append("<f2></f2>");
            str.Append("<f3></f3>");
            str.Append("<f4></f4>");
            str.Append("<f5></f5>");
            str.Append("</memberinfo>");
            return str.ToString();
        }
    }
}